package com.kk.my_pro.base.common.oauth2;


import com.kk.my_pro.config.MyAuthenticationFailureHandler;
import com.kk.my_pro.config.MyAuthenticationSuccessHandler;
import com.kk.my_pro.config.MyLogoutSuccessHandler;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.RequestMatcher;

import static org.springframework.security.config.Customizer.withDefaults;

/**
 * 授权服务器（模仿springSecurity框架源码的OAuth2AuthorizationServerConfiguration这个类）
 */
@Configuration
@Order(2)
@AllArgsConstructor
public class OAuth2ConfigurationAdapter {
    private final static String[] ALLOW_PATH_PATTERNS = {"/oauth2/**","/login"}; //定义无需认证授权得路径

    /**
     * springSecurity默认的过滤器链（可不写）
     *
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer();
        RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher();

        // 开启授权保护
        http.authorizeHttpRequests(
                        authorize -> authorize
//                                .requestMatchers("/user/list").hasAuthority("USER_LIST") // 接口user/list，只能由USER_LIST角色操作
//                                .requestMatchers("/user/add").hasAuthority("USER_ADD") // 接口user/add，只能由USER_ADD角色操作
                                .requestMatchers("/user/**").hasRole("ADMIN") // 该角色可以访问/user下所有接口
                                .anyRequest() // 对所有请求开启授权保护
                                .authenticated() // 已认证的请求会被自动授权
                )
                .formLogin(form -> {
                    form.successHandler(new MyAuthenticationSuccessHandler()) //认证成功时的处理
                            .failureHandler(new MyAuthenticationFailureHandler())//认证失败时的处理
                    ;
                }); // 使用表单授权方式
        http.logout(logout -> {
            logout.logoutSuccessHandler(new MyLogoutSuccessHandler());//退出登录，注销成功时的处理
        });
//        http.exceptionHandling(logout -> {
//            logout.authenticationEntryPoint(new MyAuthenticationEntryPoint());//请求未认证的处理
//        });
        http.csrf(withDefaults()); // 允许跨越
        //.httpBasic(withDefaults()); // 使用基本授权方式
        http.csrf(csrf -> csrf.disable()); // 关闭csrf防御
        return http.build();
    }


}
